﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Configuration;
using MINERP.InfoConfig.Version;
using MINERP.COM;
using MINERP.BLL.InfoConfig;
using MINERP.BLL.GenerateReports;


namespace MINERP.InfoConfig
{
    public partial class FrmLogin : Form
    {
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(int hWnd, int hWndlnsertAfter, int X, int Y, int cx, int cy, uint Flags);
        //private Icon mNetTrayIcon = new Icon("Tray.ico");
        ////private Icon mNetTrayIcon = new Icon(MINERP.InfoConfig.Properties.Resources.tray);
        
        //private NotifyIcon TrayIcon;
        //private ContextMenu notifyiconMnu;

        //设置服务IP，设置TCP端口号


        static IPAddress groupAddress = IPAddress.Parse("255.255.255.255"); //广播地址

        IPEndPoint ipep = new IPEndPoint(groupAddress, 8001);
        UdpClient server;

        StatisticsBLL _bll = new StatisticsBLL();

        public FrmLogin()
        {
            int a = (int)FindWindow(null, "用户登录");
            if (a > 0)
            {
                SetWindowPos(a, 0, 450, 300, 423, 195, 0x40);//激活登录窗体

                Environment.Exit(0);
            }
            InitializeComponent();
            //Initializenotifyicon();
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            //frmPackageMain = new FrmPackageMain();
            //frmPackageMain.Show();
            try
            {
                WriteLogForCheck.CreateLogFile();
            }
            catch
            {
                MessageBox.Show("创建日志文件失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            //bool check;
            //string configure;
            //configure = ConfigurationSettings.AppSettings["firstTimeLogin"].ToString();

            //server = new UdpClient(2526);

            //check = Convert.ToBoolean(configure);
            //if (check)
            //{
            //    timer1.Enabled = false;
            //}
            //else
            //{
            //    timer1.Enabled = true;
            //}
            //timer2.Enabled = true;
            //Thread t1 = new Thread(new ThreadStart(Statistics));
            //t1.Start();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            LoginBLL bll = new LoginBLL();
            if (this.txtLoginName.Text == "")
            {
                MessageBox.Show("用户账号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtLoginName.Focus();
                return;
            }
            if (this.txtLoginPWD.Text == "")
            {
                MessageBox.Show("用户密码不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtLoginPWD.Focus();
                return;
            }
            bool check;
            check = Convert.ToBoolean(ConfigurationSettings.AppSettings.Get("firstTimeLogin"));
            if (check && txtLoginName.Text.Trim().ToLower() == "admin")//是第一次登陆

            {

                //FrmDBManage frmManage = FrmDBManage.CreateInstance;
                //frmManage.Show();
                this.Visible = false;
                txtLoginName.Text = string.Empty;
                txtLoginPWD.Text = string.Empty;
            }
            else
            {
                if (bll.Login(txtLoginName.Text, MD5HashCode.GetHash( txtLoginPWD.Text)))
                {
                    this.Hide();
                    FrmInfoConfig frmmain = FrmInfoConfig.CreateInstance; ;
                    frmmain.Show(this);
                    txtLoginName.Text = "";
                    txtLoginPWD.Text = "";
                    txtLoginName.Focus();
                }
                else
                {
                    MessageBox.Show("账号密码错误", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
        /// <summary>
        /// 发送UDP
        /// </summary>
        public void SendMessage()
        {
            string version = string.Empty;
            string updatePath = string.Empty;
            VersionManager ver = new VersionManager();
            ver.GetVersionNum(out version, out updatePath);
            byte[] data = new byte[1024];
            string computerName;
            IPAddress[] ipAddress;
            computerName = Dns.GetHostName();
            ipAddress = Dns.GetHostAddresses(computerName);
            string connectString = ConfigurationManager.ConnectionStrings["newSampleYPDBEntities"].ConnectionString;
            //定义网络类型，数据连接类型和网络协议UDP
            string message = connectString;
            message = message.Substring(message.IndexOf("Data Source"));
            message = message.Substring(0, message.IndexOf(";MultipleActiveResultSets=False"));
            message = message + "|" + computerName + "(" + ipAddress[0].ToString() + ")";
            message = message + "|" + version;
            message = message + "|" + updatePath;
            data = Encoding.Unicode.GetBytes(message);

            try
            {
                server.Send(data, data.Length, ipep);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        private void Initializenotifyicon()
        {
            //设定托盘程序的各个属性

            //TrayIcon = new NotifyIcon();
            //TrayIcon.Icon = mNetTrayIcon;
            //TrayIcon.Text = "后台管理程序";
            //TrayIcon.Visible = true;
            //TrayIcon.DoubleClick += new System.EventHandler(this.doube_click);

            //定义一个MenuItem数组，并把此数组同时赋值给ContextMenu对象
            /*MenuItem[] mnuItms = new MenuItem[3];
            mnuItms[0] = new MenuItem();
            mnuItms[0].Text = "显示登录界面";
            mnuItms[0].Click += new System.EventHandler(this.showmessage);

            mnuItms[1] = new MenuItem("-");

            mnuItms[2] = new MenuItem();
            mnuItms[2].Text = "退出系统";
            mnuItms[2].Click += new System.EventHandler(this.ExitSelect);
            mnuItms[2].DefaultItem = true;

            notifyiconMnu = new ContextMenu(mnuItms);
            TrayIcon.ContextMenu = notifyiconMnu;*/
            //为托盘程序加入设定好的ContextMenu对象
        }

        public void doube_click(object sender, System.EventArgs e)
        {
            txtLoginName.Focus();
            this.Show();
        }

        public void showmessage(object sender, System.EventArgs e)
        {
            int a = (int)FindWindow(null, "用户登录");
            if (a > 0)
            {
                SetWindowPos(a, 0, 450, 300, 423, 195, 0x40);//激活登录窗体

            }
        }

        public void ExitSelect(object sender, System.EventArgs e)
        {
            DialogResult dr = MessageBox.Show("这是服务器程序，你确定退出吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                //隐藏托盘程序中的图标
                //TrayIcon.Visible = false;
                //关闭系统
                Application.Exit();
                //Environment.Exit(0);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //try
            //{
            //    SendMessage();
            //}
            //catch (Exception ex)
            //{
            //    if (ex is SocketException)
            //    {
            //        Thread.Sleep(500);
            //    }
            //}
        }
        private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            //e.Cancel = true;
            //if (e.CloseReason == CloseReason.UserClosing)
            //{
            //    e.Cancel = true;
            //    this.Hide();
            //}
            //else
            //{
            //    TrayIcon.Visible = false;
            //    if (frmPackageMain != null)
            //    {
            //        frmPackageMain.CloseForm();
            //    }
            //}

        }

        private void Statistics()
        {
            while (true)
            {
                Thread.Sleep(TimeSpan.FromHours(2));

                _bll.Statistics();

            }
 
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            int hour = 4;
            if (DateTime.Now.Hour == hour && DateTime.Now.Minute == 0 && DateTime.Now.Second == 0)//早上4点
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(DateTime.Now +"Remove Data Start");
                WriteLogForCheck.WriteLogFile(sb);
                timer3.Enabled = false;
                //_bll.MoveData();
                timer3.Enabled = true;
                StringBuilder sb1 = new StringBuilder();
                sb1.Append(DateTime.Now+"Remove Data OK");  
                WriteLogForCheck.WriteLogFile(sb1);
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {

        }
    }
}
